/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.util;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 *
 * @author GiangLT
 */
public class Hex {

    public static String convertBinary2Hexadecimal(byte[] binary) {
        String HEX_STRING = "0123456789abcdef";
        StringBuilder buf = new StringBuilder();
        int block;

        for (int i = 0; i < binary.length; i++) {
            block = binary[i] & 0xFF;
            buf.append(HEX_STRING.charAt(block >> 4));
            buf.append(HEX_STRING.charAt(binary[i] & 0x0F));
        }

        return buf.toString();
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String stringToHex(String str) {
        char[] chars = str.toCharArray();
        StringBuilder strBuffer = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            strBuffer.append(integerToHex((int) chars[i]));
        }
        return strBuffer.toString();
    }

    public static String integerToHex(int i) {
//        ByteBuffer b = ByteBuffer.allocate(4);
//        b.putInt(i);
//        byte[] array = Arrays.copyOfRange(b.array(), 3, 4);//chi lay byte cuoi
//        return convertBinary2Hexadecimal(array);

        if (i < 16) {
            return "0" + Integer.toHexString(i);
        }

        return Integer.toHexString(i);
    }

    public static void main(String[] args) {

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            ByteBuffer b = ByteBuffer.allocate(4);
            b.putInt(i);
            byte[] array1 = Arrays.copyOfRange(b.array(), 3, 4);
            System.out.println(i + ":" + convertBinary2Hexadecimal(b.array()) + ":" + convertBinary2Hexadecimal(array1));
        }
    }
}
